<template>
  <div class="hero" :class="is_dark ? 'bg-dark' : 'bg-gray'">
    <div class="form-group">
      <input class="form-input" type="text" placeholder="在此搜索" @keyup.enter="search" v-model="text">
      <button class="btn btn-primary" @click="search">搜索</button>
    </div>
    <div v-show="is_loading" class="loading loading-lg"></div>
    <div v-show="is_searched && !is_loading" class="question">
      <Question />
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import Question from '@/components/Question'

export default {
  name: 'Search',
  components: {
    Question
  },
  data() {
    return {
      is_loading: true,
      is_searched: false,
      text: ''
    }
  },
  computed: mapState(['is_dark', 'user_answer']),
  created() {
    this.$store.commit('set_curr_status', 'recite')
    this.user_answer.splice(0, this.user_answer.length)
    this.$store.commit('set_index', 0)
    this.$store.commit('set_ques_status', [null])
    this.is_loading = false
  },
  methods: {
    search() {
      this.is_loading = true
      this.$axios.post('/api/query_que', {
        text: this.text
      }).then(res => {
        const que = res.data.data
        this.$store.commit('set_questions', [que])
        this.$store.commit('set_ques_status', [null])
        if (que.questionType === 'radio') {
          this.user_answer[0] = que.answer
        } else if (que.questionType === 'checkbox') {
          this.user_answer[0] = que.answer.split(',')
        } else if (que.questionType === 'fillblank') {
          this.user_answer[0] = Array.from({ length: que.options.length }, () => '')
          for (let j = 0; j < que.options.length; j++) {
            this.user_answer[0][j] = que.options[j].content
          }
        } else {
          this.user_answer[0] = que.answer
        }
        this.is_loading = false
        this.is_searched = true
      }).catch(err => {
        this.is_loading = false
        this.is_searched = false
        console.error(err)
      })
    }
  }
}

</script>

<style scoped>
.form-group {
  display: flex;
  flex-direction: row;
  align-items: center;
}

input {
  flex: 8;
}

button {
  flex: 1;
}
</style>
